package cn.xiaopengstack.domain.strategy.service.rule.chain.impl;

import cn.xiaopengstack.domain.strategy.model.entity.RuleChainMatterEntity;
import cn.xiaopengstack.domain.strategy.model.entity.RuleChainResultEntity;
import cn.xiaopengstack.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import cn.xiaopengstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author jiangyangang
 */
@Component("rule_weight")
@Slf4j
public class RuleWeightChainImpl extends AbstractLogicChain{
    @Override
    protected DefaultLogicChainFactory.LogicModel ruleModel() {
        return DefaultLogicChainFactory.LogicModel.RULE_WEIGHT;
    }

    @Override
    public DefaultLogicChainFactory.StrategyAwardVO doChain(RuleChainMatterEntity ruleChainMatterEntity) {
        String weightRuleModel = strategyRepository.queryStrategyRuleValue(ruleChainMatterEntity.getStrategy().getStrategyId(), ruleModel().getCode());

        // 查询用户总分数
        Integer score = raffleActivityQuotaService.queryActivityAccountPartakeCount(ruleChainMatterEntity.getActivityId(), ruleChainMatterEntity.getUser().getUserId());


        String[] weightRuleLevel = weightRuleModel.split(Constants.SPACE);
        List<Long> weightList = Stream.of(weightRuleLevel).map(weightRule -> Long.valueOf(weightRule.split(Constants.COLON)[0])).collect(Collectors.toList());

        Optional<Long> chooseWeightOpt = weightList.stream()
                .sorted(Comparator.reverseOrder())
                .filter(weight -> score >= weight)
                .findFirst();

        // 处于权重范围
        if (chooseWeightOpt.isPresent()) {
            Integer awardId = strategyDispatch.getRandomAwardId(ruleChainMatterEntity.getStrategy().getStrategyId(), ruleModel().getCode());
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", ruleChainMatterEntity.getUser().getUserId(), ruleChainMatterEntity.getStrategy().getStrategyId(), ruleModel(), awardId);
            return DefaultLogicChainFactory.StrategyAwardVO.builder()
                    .takeOverRule(ruleModel())
                    .awardId(awardId)
                    .strategyId(ruleChainMatterEntity.getStrategy().getStrategyId())
                    .build();
        }

        // 放行执行其他链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", ruleChainMatterEntity.getUser().getUserId(), ruleChainMatterEntity.getStrategy().getStrategyId(), ruleModel());
        return next().doChain(ruleChainMatterEntity);
    }
}
